package com.sk.ccflower.server.common.xmlRpcManager;

import java.io.File;
import java.net.URL;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.server.PropertyHandlerMapping;
import org.apache.xmlrpc.server.XmlRpcServerConfigImpl;
import org.apache.xmlrpc.webserver.XmlRpcServlet;

import com.sk.ccflower.server.lib.dbUtils.ConnectionPoolManager;
import com.sk.ccflower.server.lib.sysUtils.Environment;


public class ModXmlRpcServlet extends XmlRpcServlet
{
	private static final long serialVersionUID=80000001L;
	/**
	 * property 파일명
	 */
	private String m_propertyFilename = null;
	private ConnectionPoolManager mConnectionPool = null;
	
	public ModXmlRpcServlet( String _propertyFilename) {
		if(_propertyFilename!=null) m_propertyFilename = new String(_propertyFilename);
	}
	
	public void setDbPool( ConnectionPoolManager _dbcp ) {
		this.mConnectionPool = _dbcp;
	}
	
	@Override
	public void init(ServletConfig pConfig) throws ServletException
	{
		super.init(pConfig);

    	try {
		    XmlRpcServerConfigImpl serverConfig = (XmlRpcServerConfigImpl) getXmlRpcServletServer().getConfig();
		    serverConfig.setEnabledForExtensions(true);
		    serverConfig.setContentLengthOptional(false);
		} catch (Exception  e) {
			throw new ServletException("Servlet initialization error: " + e.toString());
		}
	}

	/** Creates a new handler mapping. The default implementation loads
	 * a property file from the resource
	 * <code>org/apache/xmlrpc/webserver/XmlRpcServlet.properties</code>
	 * default property가 아닌 constructor에서 입력된 property파일을 이용하여 handler mapping을 만든다.
	 */
	@Override
	protected PropertyHandlerMapping newXmlRpcHandlerMapping() throws XmlRpcException
	{
		URL url = null;
		
		try {
			if(m_propertyFilename==null) url = XmlRpcServlet.class.getResource("XmlRpcServlet.properties");
			else url = new URL("file://" + File.separator + Environment.getCfgXmlrpcDir() + File.separator + m_propertyFilename);
		} catch (Exception e) {
			throw new XmlRpcException("Fail to load URL " + url, e);
		}
		
		if (url == null) {
			throw new XmlRpcException("Failed to locate resource " + url);
		}
		
		return new MyPropertyHandlerMapping( this, this.mConnectionPool, url );
		
		/*
		try {
			return newPropertyHandlerMapping(url);
		} catch (IOException e) {
			throw new XmlRpcException("Failed to load resource " + url + ": " + e.getMessage(), e);
		}
		*/
    }
}
